package com.airpi.heavy_tasks;

import android.os.AsyncTask;

import com.airpi.activities.MainMiddleFragment;
import com.airpi.activities.Observer;

/**
 * @author Antoine
 * @param mainFragment : Fragment which instanciate the AsyncTask
 * @param command : The command which needs to be sent
 * 
 * Class handling the creation of a AsyncTask (Asynchronous task) in the fragment desired, and sending the desired request
 */

public class AsyncTaskFragment extends AsyncTask<Void, Integer, String>{
	
	private static String ip; // ip where to send requests
	private MainMiddleFragment mainFragment;
	private Observer observer;
	private String command;

	public AsyncTaskFragment(MainMiddleFragment mainFragment, Observer observer, String command){
		this.mainFragment = mainFragment;
		this.observer = observer;
		this.command = command;
	}
	
	public AsyncTaskFragment(Observer observer, String command){
		this.mainFragment = null;
		this.observer = observer;
		this.command = command;
	}

	/** 
	 * Method called after onPreExecute(), which allows to execute the Heavy tasks in the background of the Fragment
	 */

	@Override
	protected String doInBackground(Void... arg) {
	
		//Create the new Connection to the server and send the request 
		Connexion co = new Connexion(ip);
		co.sendToServer(this.command);

		//On recupere la reponse du serveur
		String serverAnswer = co.answerFromServer();
		return serverAnswer;
	}

	/**
	 * Method calling the setter of the Fragment to update their values
	 */
	protected void onPostExecute(String result) {
		if (mainFragment != null)
			mainFragment.setSpinnerURL(false);
		System.out.println(result);
		((Observer)this.observer).notifier(result);
	}
	
	public static void setIP(String ipString){
		ip = ipString;
	}
}
